package com.huihui.vueadminapi.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huihui.vueadminapi.common.lang.Result;
import com.huihui.vueadminapi.entity.SysMenu;
import com.huihui.vueadminapi.entity.SysRoleMenu;
import com.huihui.vueadminapi.entity.SysUser;
import com.huihui.vueadminapi.service.SysMenuService;
import com.huihui.vueadminapi.service.SysRoleMenuService;
import com.huihui.vueadminapi.service.SysUserService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * (SysMenu)表服务控制层
 *
 * @author liyonghui
 * @since 2022-04-14 14:09:15
 */
@Api(tags = "(SysMenu)")
@Validated
@RestController
@AllArgsConstructor
@RequestMapping("/sys/menu")
public class SysMenuController extends  BaseController{


    /**
     * 获取当前用户的菜单栏以及权限
     */
    @GetMapping("/nav")
    public Result nav(Principal principal) {
        String username = principal.getName();
        SysUser sysUser = sysUserService.getByUserName(username);
        // ROLE_Admin,sys:user:save
        String[] authoritys = StringUtils.tokenizeToStringArray(
                sysUserService.getUserAuthorityInfo(sysUser.getId())
                , ",");
        return Result.succ(
                MapUtil.builder()
                        .put("nav", sysMenuService.getcurrentUserNav())
                        .put("authoritys", authoritys)
                        .map()
        );
    }

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result info(@PathVariable(name = "id") Long id) {
        return Result.succ(sysMenuService.getById(id));
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result list() {

        List<SysMenu> menus = sysMenuService.tree();
        return Result.succ(menus);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result save(@Validated @RequestBody SysMenu sysMenu) {

        sysMenu.setCreated(new Date());

        sysMenuService.save(sysMenu);
        return Result.succ(sysMenu);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result update(@Validated @RequestBody SysMenu sysMenu) {

        sysMenu.setUpdated(new Date());

        sysMenuService.updateById(sysMenu);

        // 清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return Result.succ(sysMenu);
    }

    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result delete(@PathVariable("id") Long id) {

        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if (count > 0) {
            return Result.fail("请先删除子菜单");
        }

        // 清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(id);

        sysMenuService.removeById(id);

        // 同步删除中间关联表
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id", id));
        return Result.succ("");
    }
}

